package com.example.demo.controller;

import com.example.demo.VO.CartVo;
import com.example.demo.service.CartService;
import com.example.demo.service.impl.CartServiceimpl;
import com.example.demo.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
public class CartController extends BaseController{
    @Resource
    private CartService cartService;

    @PostMapping("{pid}/add_to_cart")
    public JsonResult<Void> addToCart(@PathVariable("pid")Integer pid,HttpSession session) throws CartServiceimpl.InsertException, CartServiceimpl.UpdateException {
        System.out.println(session.getAttribute("uid").toString());
        cartService.addToCart(getUidFromSession(session),pid);
        return new JsonResult<>(OK);
    }

    @PostMapping({"/cart"})
    public JsonResult<List<CartVo>> getVOByUid(HttpSession session) {
        List<CartVo> data = cartService.getVOByUid(getUidFromSession(session));
        return new JsonResult<>(OK, data);
    }

    @PostMapping("{cid}/num/add")
    public JsonResult<Integer> addNum(@PathVariable("cid") Integer cid, HttpSession session) throws CartServiceimpl.CartNotFoundException, CartServiceimpl.UpdateException, CartServiceimpl.AccessDeniedException {
        Integer data = cartService.addNum(cid, getUidFromSession(session));
        return new JsonResult<>(OK, data);
    }

    @PostMapping("{cid}/num/reduce")
    public JsonResult<Integer> reduceNum(@PathVariable("cid") Integer cid, HttpSession session) throws CartServiceimpl.CartNotFoundException, CartServiceimpl.UpdateException, CartServiceimpl.AccessDeniedException {
        Integer data = cartService.reduceNum(cid, getUidFromSession(session));
        return new JsonResult<>(OK, data);
    }

    @PostMapping("{cid}/deleteItem")
    public JsonResult<Void> deleteItem(@PathVariable("cid")Integer cid,HttpSession session) throws CartServiceimpl.UpdateException {
        cartService.deleteItem(cid,getUidFromSession(session));
        return new JsonResult<>(OK);
    }


}
